package com.hzqy.commons.utils;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XMLUtil {
	
	
	@SuppressWarnings("unchecked")
	public static final <T> T parseXML(String xml, Class<T> cls){
		try {
			Document document = DocumentHelper.parseText(xml);
			T t = cls.newInstance();
			Element root = document.getRootElement();
			Iterator<Element> it = root.elementIterator();
			while(it.hasNext()){
				Element e = it.next();
				String text = e.getTextTrim();
				ReflectionUtils.setFieldValue(t, e.getName(), text);
			}
			return t;
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}  
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static final Map<String, Object> parseXML(String xml){
		try {
			Map<String, Object> map = new TreeMap<String, Object>();
			Document document = DocumentHelper.parseText(xml);
			Element root = document.getRootElement();
			Iterator<Element> it = root.elementIterator();
			while(it.hasNext()){
				Element e = it.next();
				map.put(e.getName(), e.getTextTrim());
			}
			return map;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	public static final String createXMLStr(Map<String, Object> map){
		Document document = DocumentHelper.createDocument();
		Element xml = document.addElement("xml");
		appendMap(xml, map);
		return document.asXML();
	}
	
	@SuppressWarnings("unchecked")
	private static final void appendMap(Element ele, Map<String, Object> map){
		Iterator<Entry<String, Object>> it = map.entrySet().iterator();
		while(it.hasNext()){
			Entry<String, Object> field = it.next();
			Element e = ele.addElement(field.getKey());
			Object val = field.getValue();
			if(val instanceof Map){
				appendMap(e, (Map<String, Object>) val);
			}else{
				e.setText(String.valueOf(field.getValue()));
			}
		}
	}
	
}
